﻿using MCPlatform.Components;
using MCPlatform.Models;
using MCPlatform.MotionLib.Base.AssitantClass;
using MCPlatform.MotionLib.Base.Environment;
using MCPlatform.UI.Components;
using Panuon.WPF.UI;
using System;
using System.Linq;
using System.Windows;
using System.Windows.Documents;

namespace MCPlatform.ViewModels.Shell
{
    public class SettingsViewModel : ViewModelBase
    {

        #region Fields

       
        #endregion



        #region Properties


        public SettingModel SettingModel
        {
            get 
            {
                
                return _settingModel;
            }

            set
            {
               
                Set(ref _settingModel, value);
               

            }
        }
        private SettingModel _settingModel = new SettingModel();

        #endregion


        #region Events

        public static event Action<double>? SetVelocityEvent;

        #endregion

      
        #region Methods

        public void LoadCofig()
        {
                       
            SettingModel = ReadConfigData.GetParaConfigs<SettingModel>(Paths.SettingConfigPaths)?.FirstOrDefault() ?? new SettingModel();

            

        }


        public void ConfigSave()
        {
        
            SaveConfigData.SaveConfig<SettingModel>(Paths.SettingConfigPaths, SettingModel);
           
        }

        public void SetVelocity(double velRate)
        {
            VeloctyRate = velRate;
            SetVelocityEvent?.Invoke(velRate);
        }
        public void SetAutoStart(bool enable)
        {
            bool res = AutoStartup.SetAutoStart(enable);
            string OnOrOff = enable ? "设置" : "取消";
            string result = res ? "成功" : "失败";
            Toast.Show($"{OnOrOff}开机自启动{result}!", targetWindow: ToastWindow.MainWindow);
        }

        #endregion

        public SettingsViewModel()
        {
            LoadCofig();

            //加载时候设置下速度
            SetVelocity(SettingModel.VelocityRate);

            //设置生产模式
            ProductionMode = SettingModel.ProductionMode;
            AutomaticSubMode = SettingModel.AutomaticSubMode;
        }


        public void Apply()
        {
            var config = ReadConfigData.GetParaConfigs<SettingModel>(Paths.SettingConfigPaths)?.FirstOrDefault() ?? new SettingModel();

            if (config.IsAutoStart != SettingModel.IsAutoStart)
            {
                SetAutoStart(SettingModel.IsAutoStart);
            }



            if (config.VelocityRate != SettingModel.VelocityRate)
            {
                SetVelocity(SettingModel.VelocityRate);
            }

            ProductionMode = SettingModel.ProductionMode;

            AutomaticSubMode = SettingModel.AutomaticSubMode;

            ConfigSave();
        }



    }
}
